﻿using System;
using System.Linq;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Framework.Client;
using Microsoft.LightSwitch.Presentation;
using Microsoft.LightSwitch.Presentation.Extensions;
using System.Windows.Controls;
namespace LightSwitchApplication
{
    public partial class CustomProperties
    {
        partial void CustomProperties_Created()
        {
            // Making the IsBoundStatically Property read only!
            // This solution comes from 
            // http://social.msdn.microsoft.com/Forums/en-US/lightswitch/thread/8fc66ea7-1b31-46ca-9a20-58806a01e83e
            this.FindControl("gridProperties").ControlAvailable += 
                new EventHandler<ControlAvailableEventArgs>(CustomPropertiesGrid_ControlAvailable);
            this.FindControl("gridChoices").ControlAvailable += 
                new EventHandler<ControlAvailableEventArgs>(ChoicesGrid_ControlAvailable);
        }

        private void ChoicesGrid_ControlAvailable(object sender, ControlAvailableEventArgs e)
        {
            DataGrid dataGrid = (DataGrid)e.Control;

            // Make the second column read-only (skip the first and take the third).
            // This solution works even if the end user rearranges the columns.
            dataGrid.Columns.Skip(1).First().IsReadOnly = true;
        }

        private void CustomPropertiesGrid_ControlAvailable(object sender, ControlAvailableEventArgs e)
        {
            DataGrid dataGrid = (DataGrid)e.Control;

            // Make the third column read-only (skip the first two and take the third).
            // This solution works even if the end user rearranges the columns.
            dataGrid.Columns.Skip(2).First().IsReadOnly = true;


        }

        partial void CustomPropertiesSorted_SelectionChanged()
        {
            if (this.CustomPropertiesSorted.SelectedItem == null)
                return;

            if (this.CustomPropertiesSorted.SelectedItem.IsChooseable == true)
                setIsEnabledSavely("gridChoices", true);
            else
                setIsEnabledSavely("gridChoices", false);
        }

        /// <summary>
        /// This method checks the state of IsEnabled before  changing it.
        /// This is done to prevent loops by changed properties.
        /// ToDo: Extend method to deal with any property and move it in helper class.
        /// </summary>
        /// <param name="strControl"></param>
        /// <param name="bIsEnabled"></param>
        private void setIsEnabledSavely(string strControl, bool bIsEnabled)
        {
            var ctrl = this.FindControl(strControl);
            if (ctrl.IsVisible != bIsEnabled)
                ctrl.IsVisible = bIsEnabled;
        }
    }
}
